<template>
  <div class="new-chat-container">
    <!-- 标题区域：简化为居中标题 -->
    <div class="new-chat-header">
      <h2 class="new-chat-title">AI聊天</h2>
      <!-- <p class="new-chat-subtitle">构建你的AI助手</p> -->
    </div>

    <!-- 聊天内容区域 -->
    <div class="new-chat-messages" ref="messagesContainer">
      <div 
        v-for="(msg, idx) in messages" 
        :key="idx" 
        :class="['new-message', { self: msg.isSelf, error: msg.isError }]"
      >
        <div class="new-message-content" v-html="formatMessage(msg.text)"></div>
        <div class="new-message-time">{{ formatTime(msg.timestamp) }}</div>
      </div>

      <!-- 加载中动画 -->
      <div v-if="isLoading" class="new-message loading">
        <div class="new-message-content animate-pulse">
          <div class="h-3 bg-gray-300 rounded w-16 mb-2"></div>
          <div class="h-3 bg-gray-300 rounded w-32 mb-2"></div>
          <div class="h-3 bg-gray-300 rounded w-24"></div>
        </div>
      </div>
    </div>

    <!-- 输入发送区域：贴合题图样式 -->
    <div class="new-chat-input-area">
      <div class="new-input-wrapper">
        <input 
          v-model="inputVal" 
          class="new-chat-input"
          placeholder="请输入消息"
          @keyup.enter="sendMessage"
        />
        <button 
          class="new-send-btn"
          @click="sendMessage"
          :disabled="isLoading"
        >
          发送
        </button>
      </div>
    </div>
  </div>
</template>

<script>
// import axios from 'axios';
import qs from 'qs';
export default {
  data() {
    return {
      inputVal: '',
      messages: [],
      isLoading: false,
      // 保留聊天记录存储标识
      currentChatId: localStorage.getItem('currentChatId') || `chat_${Date.now()}`,
    };
  },
  mounted() {
    this.loadChatHistory();
  },
  methods: {
      scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        // 等待 DOM 更新后再滚动（确保新消息已渲染）
        this.$nextTick(() => {
          container.scrollTop = container.scrollHeight;
        });
      }
    },
    async sendMessage() {
      if (this.isLoading || !this.inputVal.trim()) return;

      // 添加用户消息
      const userMessage = {
        text: this.inputVal,
        isSelf: true,
        isError: false,
        timestamp: new Date().toISOString()
      };
      this.messages.push(userMessage);
      this.saveChatHistory();
        this.scrollToBottom(); // 新增：用户消息发送后滚动

      // 清空输入框
      this.inputVal = '';
      this.isLoading = true;
try {
  // 使用 fetch API 替代 axios
  const response = await fetch('http://localhost:8080/ai/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: qs.stringify({
      prompt: userMessage.text,
      chatId: this.currentChatId
    })
  });

  // 处理流式响应
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let aiReply = '';
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    aiReply += decoder.decode(value, { stream: true });
    
    // 更新最后一条消息为 AI 回复
    this.messages[this.messages.length - 1] = {
      text: aiReply,
      isSelf: false,
      isError: false,
      timestamp: new Date().toISOString()
    };
    
    this.saveChatHistory();
      this.scrollToBottom(); // 新增：用户消息发送后滚动
  }
} catch (error) {
  console.error('调用AI接口失败：', error);
  // 添加错误消息
  this.messages.push({
    text: '请求失败，请稍后重试',
    isSelf: false,
    isError: true,
    timestamp: new Date().toISOString()
    
  });
    this.scrollToBottom(); // 新增：用户消息发送后滚动
} finally {
  this.isLoading = false;
  this.saveChatHistory();
}
    },

    formatMessage(text) {
      // 简单的Markdown解析（保留原逻辑）
      if (!text) return '';

      // 转换URL为链接
      const urlRegex = /(https?:\/\/[^\s]+)/g;
      const textWithLinks = text.replace(urlRegex, '<a href="$1" target="_blank">$1</a>');

      // 转换换行符
      return textWithLinks.replace(/\n/g, '<br>');
    },

    formatTime(timestamp) {
      // 时间格式化（保留原逻辑）
      const date = new Date(timestamp);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },

    saveChatHistory() {
      // 本地存储聊天记录（保留原逻辑）
      localStorage.setItem(`chat_messages_${this.currentChatId}`, JSON.stringify(this.messages));
      localStorage.setItem('currentChatId', this.currentChatId);
    },

    loadChatHistory() {
      // 加载历史记录（保留原逻辑）
      const savedMessages = localStorage.getItem(`chat_messages_${this.currentChatId}`);
      if (savedMessages) {
        this.messages = JSON.parse(savedMessages);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
/* 容器整体：更柔和的卡片感 */
.new-chat-container {
  width: 500px; 
  margin: 40px auto;
  border-radius: 12px; /* 增大圆角更柔和 */
  box-shadow: 0 4px 12px rgba(0,0,0,0.06); /* 阴影更细腻 */
  overflow: hidden;
  background: #fff; /* 容器底色统一 */
}

/* 标题区域：弱化分割感 */
.new-chat-header {
  padding: 20px;
  text-align: center;
  background: linear-gradient(120deg, #e3f2fd 0%, #f5faff 100%); /* 渐变让头部更灵动 */
  border-bottom: 1px solid #f1f5f9; /* 浅分割线 */

  .new-chat-title {
    font-size: 20px;
    font-weight: 600;
    color: #2c3e50; /* 深一点的文字色更清晰 */
    margin: 0; /* 去掉默认边距 */
  }

  .new-chat-subtitle {
    font-size: 14px;
    color: #90a4ae; /* 浅灰色更柔和 */
    margin: 4px 0 0; /* 调整边距 */
  }
}

/* 聊天内容区域：优化滚动体验 & 气泡感 */
.new-chat-messages {
  max-height: 400px; /* 固定最大高度，超出滚动 */
  height: 400px;     /* 明确高度，避免内容变化导致塌陷 */
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 18px;
  background: #f9fafb;

  /* 滚动条样式保持不变 */
  &::-webkit-scrollbar { width: 6px; }
  &::-webkit-scrollbar-track { background: #f9fafb; }
  &::-webkit-scrollbar-thumb { 
    background: #d1d5db; 
    border-radius: 3px; 
  }
  }

/* 消息气泡：强化层次 */
.new-message {
  max-width: 70%;
  padding: 12px 16px; /* 增大内边距更舒适 */
  border-radius: 8px; 
  line-height: 1.6;
  position: relative; /* 用于时间定位 */

  &.self {
    background: #e3f2fd; 
    margin-left: auto;
    box-shadow: 0 2px 6px rgba(33,150,243,0.1); /* 轻微阴影突出用户消息 */
  }

  &.error {
    background: #ffe6e6; 
    color: #ff4d4f;
    box-shadow: 0 2px 6px rgba(255,77,79,0.1);
  }

  a {
    color: #2196f3; 
    text-decoration: underline;
    transition: color 0.2s;
    &:hover {
      color: #1976d2;
      text-decoration: none;
    }
  }
}

/* 消息内容与时间分离排版 */
.new-message-content {
  word-wrap: break-word;
  font-size: 14px;
  color: #4b5563; /* 清晰文字色 */
}

.new-message-time {
  font-size: 12px;
  color: #9ca3af; 
  text-align: right;
  margin-top: 6px;
  opacity: 0.8;
}

/* 加载中动画：更细腻的占位 */
.loading .new-message-content {
  animation: pulse 1.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
  background: #f1f5f9; /* 浅灰占位更自然 */
  border-radius: 6px;
  padding: 12px 16px; /* 与真实消息一致 */
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

/* 输入区域：操作更顺手 */
.new-chat-input-area {
  border-top: 1px solid #f1f5f9; 
  padding: 16px 20px;
  background: #fff; /* 与容器底色统一 */
}

.new-input-wrapper {
  display: flex;
  gap: 10px; /* 增大按钮间距 */
}

.new-chat-input {
  flex: 1;
  padding: 12px 14px; 
  border: 1px solid #e2e8f0; 
  border-radius: 8px; 
  outline: none;
  font-size: 14px;
  color: #4b5563;
  transition: border-color 0.2s;

  &:focus {
    border-color: #90cdf4; /* 聚焦时浅蓝边框 */
  }
}

.new-send-btn {
  padding: 12px 24px; /* 增大点击区域 */
  background: #2196f3;
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;

  &:hover {
    background: #1e88e5; /* 加深 hover 色 */
    transform: translateY(-1px); /* 轻微上移增强反馈 */
    box-shadow: 0 2px 8px rgba(33,150,243,0.2);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }
}
</style>